import Flutter
import UIKit

public class FigoPlayerPlugin: NSObject, FlutterPlugin {
  private var ffmpegWrapper: FFmpegWrapper?
  
  public static func register(with registrar: FlutterPluginRegistrar) {
    let channel = FlutterMethodChannel(name: "figo_player_plugin/engine", binaryMessenger: registrar.messenger())
    let instance = FigoPlayerPlugin()
    registrar.addMethodCallDelegate(instance, channel: channel)
  }

  public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
    switch call.method {
    case "loadMedia":
      let args = call.arguments as? [String: Any]
      let filePath = args?["filePath"] as? String
      let config = args?["config"] as? [String: Any]
      
      if let filePath = filePath {
        ffmpegWrapper = FFmpegWrapper()
        let success = ffmpegWrapper?.initialize() ?? false
        if success {
          let openSuccess = ffmpegWrapper?.openMedia(filePath) ?? false
          result(openSuccess)
        } else {
          result(false)
        }
      } else {
        result(false)
      }
      
    case "play":
      let success = ffmpegWrapper?.play() ?? false
      result(success)
      
    case "pause":
      let success = ffmpegWrapper?.pause() ?? false
      result(success)
      
    case "stop":
      let success = ffmpegWrapper?.stop() ?? false
      result(success)
      
    case "seek":
      let args = call.arguments as? [String: Any]
      let time = args?["time"] as? Double ?? 0.0
      let success = ffmpegWrapper?.seek(time) ?? false
      result(success)
      
    case "setVolume":
      let args = call.arguments as? [String: Any]
      let volume = args?["volume"] as? Double ?? 1.0
      ffmpegWrapper?.setVolume(volume)
      result(nil)
      
    case "setHardwareDecode":
      let args = call.arguments as? [String: Any]
      let enable = args?["enable"] as? Bool ?? false
      // 硬件解码设置实现
      result(nil)
      
    case "setBatteryOptimization":
      let args = call.arguments as? [String: Any]
      let enable = args?["enable"] as? Bool ?? false
      // 省电模式设置实现
      result(nil)
      
    case "setMemoryLimit":
      let args = call.arguments as? [String: Any]
      let mbLimit = args?["mbLimit"] as? Int ?? 100
      // 内存限制设置实现
      result(nil)
      
    default:
      result(FlutterMethodNotImplemented)
    }
  }
}
